#include<vector>
#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
pair<int,int> mem[100001];
struct Node{
    int curIndex;
    int key;
    int nextIndex;
};
bool msort(const Node* a, const Node* b){
    return a->key<b->key;
}
int main(){
    int n;
    int startIndex;
    cin>>n>>startIndex;
    if(startIndex==-1){
        cout<<"0 -1"<<endl;
        return 0;
    }
    int curIndex,key,nextIndex;
    int i=0;
    while(i++<n){
        cin>>curIndex>>key>>nextIndex;
        mem[curIndex]=pair<int,int>(nextIndex,key);
    }
    vector<Node*> v;
    i=0;
    while(i++<n){
        nextIndex=mem[startIndex].first;
        Node* node = new Node();
        node->curIndex=startIndex;
        node->key=mem[startIndex].second;
        node->nextIndex=nextIndex;
        v.push_back(node);
        if(nextIndex==-1)
            break;
        startIndex=nextIndex;
    }
    sort(v.begin(),v.end(),msort);
    Node* preNode = v[0];
    Node* curNode;
    for(int i=1;i<v.size();i++){
        curNode = v[i];
        preNode->nextIndex=curNode->curIndex;
        preNode=curNode;
    }
    preNode->nextIndex=-1;
    cout<<v.size()<<" "<<setw(5)<<setfill('0')<<v[0]->curIndex<<endl;
    for(int i=0;i<v.size();i++){
        if(v[i]->nextIndex>0)
            cout<<setw(5)<<setfill('0')<<v[i]->curIndex<<" "<<v[i]->key<<" "<<setw(5)<<setfill('0')<<v[i]->nextIndex<<endl;
        else
            cout<<setw(5)<<setfill('0')<<v[i]->curIndex<<" "<<v[i]->key<<" "<<v[i]->nextIndex<<endl;
    }
    return 0;
}
